package com.xiaotu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.sql.DataSource;

@EnableWebSecurity      //开启web Security安全支持
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserDetailsService userDetailsService;

    //使用内存进行身份认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //密码需要设置编码器
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //1.使用内存用户信息,作为测试使用
       /* auth.inMemoryAuthentication().passwordEncoder(encoder)
                .withUser("xiaotu").password(encoder.encode("123456")).roles("vip")
                .and()
                .withUser("user").password(encoder.encode("123456")).roles("common");*/
        //2.使用jdbc进行身份认证
      /*  String userSQL = "select username,password,valid from t_customer where username = ?";
        String authoritySQL =
                "select c.username,a.authority from t_customer c, t_authority a, t_customer_authority ca where ca.customer_id = c.id and ca.authority_id = a.id and c.username = ?";
        auth.jdbcAuthentication().passwordEncoder(encoder)
                .dataSource(dataSource)
                .usersByUsernameQuery(userSQL)
                .authoritiesByUsernameQuery(authoritySQL);*/
        //3.使用UserDetailsService进行身份验证
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
    }

    /**
     * 重写该方法进行用户访问控制
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/","/exception/**").permitAll()
                //对static文件下静态资源进行统一放行
                .antMatchers("/login/**").permitAll()
                .antMatchers("/toMoviePage/common/**").hasRole("common")
                .antMatchers("/toMoviePage/vip/**").hasRole("vip")
                .anyRequest().authenticated()
                ;
        //自定义用户登录控制
        http.formLogin()
                .loginPage("/login").permitAll()
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/")
                .failureUrl("/login?error");
        //自定义用户退出控制
        http.logout()
                .logoutUrl("/mylogout")
                .logoutSuccessUrl("/");
        //定制Remember_me记住我功能
        http.rememberMe()
                .tokenRepository(tokenRepository())
                .tokenValiditySeconds(200);
        http.exceptionHandling()
                .accessDeniedPage("/exception/403");
    }
    @Bean
    public JdbcTokenRepositoryImpl tokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }
}
